<template>
	<view class="safe-area-inset-bottom" style="padding-bottom: 160rpx;">
		<view class="pad-20" style="background-color: #fff;">
			<u--form labelPosition="left" :model="formData" :rules="rules" ref="form1" labelWidth="auto">
				<u-form-item label="企业名称:" prop="orgName" borderBottom required>
					<u--input v-model="formData.orgName" placeholder="请输入企业名称" border="none"></u--input>
				</u-form-item>
				<u-form-item label="所属地区:" prop="regionName" borderBottom required @click="pickerShow = true">
					<view class="region-v fs30">
						<div class="flex">
							<div style="width: 500rpx;">
								{{formData.regionName?formData.regionName:'请选择地区'}}
							</div>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</div>
					</view>
				</u-form-item>
				<u-form-item label="详细地址:" prop="address" borderBottom required>
					<u--input v-model="formData.address" placeholder="请输入详细地址" border="none"></u--input>
				</u-form-item>
				<u-form-item label="法人:" prop="linkman" borderBottom required>
					<u--input v-model="formData.linkman" placeholder="请输入法人姓名" border="none"></u--input>
				</u-form-item>
				<u-form-item label="统一社会信用代码:" prop="orgCode" borderBottom required>
					<u--input v-model="formData.orgCode" placeholder="请输入统一社会信用代码" border="none"></u--input>
				</u-form-item>
				<u-form-item label="营业执照:" prop="yyzzImg" borderBottom required>
					<u-upload
					name="yyzzImg" 
					accept="image" 
					useBeforeRead 
					:sizeType="['compressed']"
					:fileList="yyzzImgList"
					@afterRead="afterRead"
					@delete="deletePic" 
					:maxCount="1"
					:previewFullImage="true"></u-upload>
				</u-form-item>
				<view style="height: 10px;width: 110%;background:#f8f8f8;position: relative;left: 50%;transform: translateX(-50%);"></view>
				<u-form-item label="登录账号:" prop="username" borderBottom required>
					<u--input v-model="formData.username" placeholder="请输入自定义登录账号" border="none"></u--input>
				</u-form-item>
				<u-form-item label="登录密码:" prop="password" borderBottom required>
					<u--input type="password" v-model="formData.password" placeholder="请输登录密码" border="none">
					</u--input>
				</u-form-item>
				<u-form-item label="确认密码:" prop="password2" borderBottom required>
					<u--input type="password" v-model="formData.password2" placeholder="请再输入密码" border="none">
					</u--input>
				</u-form-item>
				<u-form-item label="联系电话:" prop="phone" borderBottom required>
					<u--input type="phone" v-model="formData.phone" placeholder="请输入联系电话" border="none">
					</u--input>
				</u-form-item>
				<u-form-item label="短信验证码:" prop="verifiableCode" borderBottom required>
					<view class="code-box">
						<u--input v-model="formData.verifiableCode" placeholder="请输入短信验证码" border="none"></u--input>
						<button
						class="btn btn-code"
						:disabled="isSendingCode || formData.phone === ''"
						@click="sendCode">
							{{ btnText }}
						</button>
					</view>

				</u-form-item>			
			</u--form>
		</view>

		<view class="safe-area-inset-bottom action-box">
			<u-button type="primary" shape="circle" text="注册" @click="saveForm"></u-button>
		</view>
		
		<u-picker 
		ref="region" 
		:show="pickerShow"
		:columns="columns"
		keyName="districtName" 
		@confirm="regionConfirm"
		@change="regionChange" 
		@cancel="pickerShow = false;"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入密码'));
				} else {
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'));
				} else if (value !== this.formData.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			var validAccount1 = async (rule, value, callback) => {
			  if (value) {
				if (/[\u4E00-\u9FA5]/g.test(value)) {
				  callback(new Error("不能输入汉字"));
				} else if (!(await this.findUser(value))) {
				  // 验证通过
				  callback(new Error("该账户已被注册"));
				} else {
				  callback();
				}
			  } else {
				callback();
			  }
			};
			return {
				formData: {

					"orgName": "",// 企业名称
					
					"provinceId": "",
					"cityId": "",	
					"districtId": "",
					"streetId": "",				
					"provinceArea": "",
					"provinceName": "",
					"cityCode": "",
					"districtCode": "",
					"streetCode": "",
					"cityArea": "",
					"cityName": "",
					"districtArea": "",
					"districtName": "",
					"streetArea": "",
					"streetName": "",
					
					"regionName": "",	
										
					"address": "",// 详细地址
					
					"linkman": "", // 法人
					 
					"orgCode": "",// 统一社会信用代码
					 
					"yyzzImg": "",// 营业执照
					 
					"username": "",
					 
					"password": "",
						 
					"phone": "",					 
					 
					"id": 0,
				    "num": 0,
					"realName": "",					  					  				  					  				 										  
					"hasOrg": false			,
					
					"password2": "",
					"verifiableCode": "",
				},
				rules: {
					password: [{
							type: 'string',
							required: true,
							message: '请填写登录密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 20,
							message: '长度在 6 到 20 个字符',
							trigger: 'blur'
						},
						{
							validator: validatePass,
							trigger: 'blur'
						}
					],
					password2: [{
							required: true,
							message: '请再次填写登录密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 20,
							message: '长度在 6 到 20 个字符',
							trigger: 'blur'
						},
						{
							validator: validatePass2,
							trigger: 'blur',
							required: true
						}
					],
					orgName: [{
						type: 'string',
						required: true,
						message: '请填写企业名称',
						trigger: ['blur', 'change']
					}],
					regionName: [
						{ required: true,message: '请选择所属地区'},
						{
							validateFunction:(rule,value,data,callback)=>{
								console.log(this.region)
								if (!this.region) {
									callback('请选择所属地区')
								}
								return true
							}
						}
					],
					address: [{
						type: 'string',
						required: true,
						message: '请填写详细地址',
						trigger: ['blur', 'change']
					}],
					linkman: [{
						type: 'string',
						required: true,
						message: '请填写法人姓名',
						trigger: ['blur', 'change']
					}],
					orgCode: [{
						type: 'string',
						required: true,
						message: '请填写统一社会信用代码',
						trigger: ['blur', 'change']
					},{
						pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
						message:'统一社会信用代码格式错误'
					}
					
					],
					yyzzImg: [
						{ required: true,message: '请上传营业执照'},
						{
							validateFunction:(rule,value,data,callback)=>{
								if (!value) {
									callback('请上传营业执照')
								}
								return true
							}
						},
					],
					username: [{
						type: 'string',
						required: true,
						message: '请输入登录账号',
						trigger: ['blur', 'change']
					},
					{ pattern: /^[a-zA-Z]([-_a-zA-Z0-9]{3,15})$/, message: '字母开头，英文、数字、下划线和减号 4-16位', trigger: 'blur' },
					{ validator: validAccount1, trigger: "blur" },
					],
					phone: [{
							required: true,
							message: '请填写联系电话',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								// 返回true表示校验通过，返回false表示不通过
								if (value) {
									return this.$u.test.mobile(value);
								} else {
									return false
								}
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					verifiableCode:[{
						type: 'string',
						required: true,
						message: '请输入短信验证码',
						trigger: ['blur', 'change']
					}],
				},
				pickerShow: false,
				yyzzImgList: [],
				columns: [[],[],[],[],],
				isSendingCode:false,
				code: '',
				isSendingCode: false,
				countDown: 60,
				btnText: '获取验证码',
				timer: null,
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		},
		onLoad() {
			this.getDistrict(0)
		},
		methods: {
			change(data) {
				console.log('地区选择信息：', data);
				this.formData.regionName = data.name.join('')
			},
			// 查找用户
			findUser(userName) {
			  return new Promise((resolve, reject) => {
				this.$api.user
				  .findUserName({
					userName: userName,
				  })
				  .then((res) => {
					if (res.data) {
					  resolve(false);
					} else {
					  resolve(true);
					}
				  });
			  });
			},
			// 获取验证码
			sendCode() {
				// 验证手机号
				this.$refs.form1.validateField('phone',(res)=>{
					if (res.length>0) {
						uni.$u.toast(res[0].message)
						return
					}
					this.isSendingCode = true;
					// 发送验证码的代码
					this.$api.user.sendCodeByPhone({phone:this.formData.phone})
					.then(res=>{
						console.log(res)
						uni.$u.toast('验证码已发送，请注意查收')
					}).catch(err=>{
						console.log(err)
						uni.showToast({title: err.message,icon:'error'});
						return
					})
					
					
					// 开始倒计时
					this.timer = setInterval(() => {
						if (this.countDown > 0) {
						  this.countDown--
						  this.btnText = `${this.countDown}秒后重发`
						} else {
						  this.isSendingCode = false
						  this.countDown = 60
						  this.btnText = '获取验证码'
						  clearInterval(this.timer)
						}
					}, 1000)
					
				})
				
			},
			// 判断验证码是否有效
			validateCodeIsTrue() {			
			  return new Promise((resolve, reject) => {
				this.$api.user.judgeCode({
					phone: this.formData.phone,
					smsCode: this.formData.verifiableCode,
				}).then((res) => {
					if (res.data) {
					  resolve(true);
					} else {
					  resolve(false);
					}
				}).catch(e=>{
					uni.$u.toast('系统错误')
					resolve(false)
				})
			  })
			},
			
			
			//获取详情
			getDistrict(pid) {
				let req_params = {
					"page": 1,
					"pageSize": 999,
					"pid": pid,
				};
				this.$api.address.district(req_params).then(({
					data
				}) => {
					console.log(data);
					let dataAry = [{
						districtName: "请选择",
						id: null,
						regionCode: null
					}]
					if (data.records && data.records.length > 0) {
						if (data.records[0].level == 1) { // 省
							dataAry[0].level == 1;
							dataAry[0].pid == pid;
							this.columns[0] = dataAry.concat(data.records);
							this.columns[1] = [];
							this.columns[2] = [];
							this.columns[3] = [];
							// this.$refs.region.setIndexs(1, 0);
							// this.$refs.region.setColumnValues(0, dataAry.concat(data.records))
						}
						if (data.records[0].level == 2) { // 市
							dataAry[0].level == 2;
							dataAry[0].pid == pid;
							this.columns[1] = dataAry.concat(data.records);
							this.columns[2] = [];
							this.columns[3] = [];
							// this.$refs.region.setIndexs(2, 0);
							// this.$refs.region.setColumnValues(1, dataAry.concat(data.records))
						}
						if (data.records[0].level == 3) { // 区/县
							dataAry[0].level == 3;
							dataAry[0].pid == pid;
							this.columns[2] = dataAry.concat(data.records);
							this.columns[3] = [];
							// this.$refs.region.setIndexs(3, 0);
							// this.$refs.region.setColumnValues(2, dataAry.concat(data.records))
						}
						if (data.records[0].level == 4) { // 乡/镇/街道
							dataAry[0].level == 4;
							dataAry[0].pid == pid;
							this.columns[3] = dataAry.concat(data.records);
							// this.$refs.region.setIndexs(4, 0);
							// this.$refs.region.setColumnValues(3, dataAry.concat(data.records))
						}

						this.columns = JSON.parse(JSON.stringify(this.columns));
					}

				}).catch(err => {
					console.log(err);
				});
			},
			// 选择地区回调
			regionConfirm(e) {
				console.log('regionConfirm=', e);
				// let idxs = e.indexs;
				let regCheck = function(idxs) {
					for (let i = 0; i < idxs.length; i++) {
						if (idxs[i] < 1) {
							return false;
						}
					}
					return true;
				}
				if (regCheck(e.indexs)) {
					this.formData.regionName = e.value[0].districtName + e.value[1].districtName + e.value[2].districtName + e.value[3].districtName;

					console.log('e',e)
					this.formData.provinceId = e.value[0].id
					this.formData.cityId = e.value[1].id
					this.formData.districtId = e.value[2].id
					this.formData.streetId = e.value[3].id
					
					this.formData.provinceArea = e.value[0].regionCode
					this.formData.cityArea = e.value[1].regionCode
					this.formData.districtArea = e.value[2].regionCode
					this.formData.streetArea = e.value[3].regionCode
					
					this.formData.provinceName = e.value[0].districtName
					this.formData.cityName = e.value[1].districtName
					this.formData.districtName = e.value[2].districtName
					this.formData.streetName = e.value[3].districtName
					console.log(this.formData)
					this.pickerShow = false;
					this.$refs.form1.validateField(['regionName'])
				} else {
					uni.$u.toast('地区信息未选择完整')
				}

			},
			// 切换地区数据列回调
			regionChange(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.region
				} = e
				// console.log('regionChange=', this.columns[columnIndex]);
				let item = this.columns[columnIndex][index];
				console.log('regionChange item=', item);
				// 当第一列值发生变化时
				if (columnIndex == 0) {
					// this.columns[1] = [];
					// picker.setIndexs(1, 0)
					// picker.setColumnValues(1, [])
				}
				if (columnIndex == 1) {
					// this.columns[2] = [];
					// picker.setIndexs(2, 0)
					// picker.setColumnValues(1, [])
				}
				if (columnIndex == 2) {
					// this.columns[3] = [];
					// picker.setIndexs(3, 0)
					// picker.setColumnValues(1, [])
				}
				if (item && item.id) {
					this.getDistrict(item.id);
				} else {

				}
				// this.form.region = e.province.label + e.city.label + e.area.label;
				// this.form.provinceName = e.province.label;
				// this.form.cityName = e.city.label;
				// this.form.districtName = e.area.label;
			},
			// 删除图片
			deletePic(event) {
				// console.log("deletePic=", event);
				this[`${event.name}List`].splice(event.index, 1)
				this.formData.yyzzImg = ""
			},
			// 新增图片
			async afterRead(event) {
				this.uploadFilePromise(event.file, event.name)
			},
			// 上传图片
			uploadFilePromise(file, name) {
				let mineTypes = file.url.split('.');
				let mineType = mineTypes[mineTypes.length - 1];
				if (!mineType || !['png', 'jpg', 'jpeg'].includes(mineType)) {
					return uni.$u.toast('请上传jpg/png格式图片')
				}
				uni.showLoading({
					mask: true,
					title: '图片上传中..'
				})
				let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2);
				let quality;
				if (fileSize < 1) {
					quality = 100;
				} else if (fileSize >= 1 && fileSize < 3) {
					quality = 50;
				} else if (fileSize >= 3 && fileSize < 5) {
					quality = 40;
				} else if (fileSize >= 5 && fileSize < 10) {
					quality = 30;
				} else if (fileSize >= 10 && fileSize < 15) {
					quality = 20;
				} else if (fileSize >= 15 && fileSize < 20) {
					quality = 10;
				} else if (fileSize >= 20 && fileSize < 25) {
					quality = 9;
				} else if (fileSize >= 25 && fileSize < 30) {
					quality = 8;
				} else if (fileSize >= 30 && fileSize < 35) {
					quality = 7;
				} else {
					quality = 6;
				}
				let that = this;
				uni.compressImage({
					src: file.url,
					quality: quality,
					success: ret => {
						// console.log(ret.tempFilePath)
						let req_params = {
							filePath: ret.tempFilePath,
							name: name
						};
						this.$api.common.uploadFile(req_params).then(res => {
							uni.hideLoading()
							if (name == 'yyzzImg') {
								this.formData.yyzzImg = res.data.filePath;
								this.yyzzImgList = [{
									url: res.data.filePath
								}]
								this.$refs.form1.validateField(['yyzzImg'])					
							}
							if (name == 'logoImg') {
								this.formData.logoImg = res.data.filePath;
								this.logoImgList = [{
									url: res.data.filePath
								}]
							}
						});
					}
				})
			
			},			
													
			saveForm() {							
				this.$refs.form1.validate().then(async (res) => {		
					//校验验证码
					let isTrue = await this.validateCodeIsTrue();
					if (!isTrue) {
						uni.$u.toast("验证码错误");
						return;
					}
					
					
					this.$api.user.register({...this.formData}).then(res => {
						if (res.code == 200) {
							if (res.data.success) {
								uni.showToast({
									mask: true,
									title: "注册成功",
									icon: "success"
								});
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/login/login'
									});
								}, 1300)
							}else {
								uni.$u.toast(res.data.message)
							}						
							
						}
					}).catch(err => {
						console.log(err)
						uni.showToast({
							mask: true,
							title: err.message,
							icon: "error"
						});
					})
				}).catch(errors => {
					console.log(errors)
					uni.$u.toast('校验失败,请检查信息是否按要求填写')
				})
			},
		}
	}
</script>

<style scoped>
	.action-box {
		width: 100%;
		height: 100rpx;
		background: white;
		position: fixed;
		bottom: 0;
		box-shadow: 0 0 20rpx rgba(182, 182, 182, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9;
	}

	.region-v {
		flex: 1;
		padding: 12rpx 18rpx;
	}
	.code-box {
		display: flex;
		
	}
	.btn-code {
	  /* padding: 8px 16px; */
	  display: inline-block;
	  font-size: 14px;
	  color: #fff;
	  background-color: #1890ff;
	  border: none;
	  border-radius: 4px;
	  cursor: pointer;
	}
	
	.btn-code:disabled {
	  background-color: #ccc;
	  cursor: not-allowed;
	}
</style>
